import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState, useEffect } from "react";
import Header from "@/pages/myComponent/header";
import LgSelepicker from "@/pages/components/selePick";
import LgSearch from "@/pages/components/searchInput";
import { Switch, Divider } from "antd-mobile";
import { useRequest } from "taro-hooks";
import debounce from "lodash.debounce";
import {
  changeSystemStatusService,
  getSettingListService,
  getSystemListService,
} from "@/network/servers";
import useGetUserInfo from "../../../hooks/useGetUserInfo";
import SpinLoad from "@/pages/myComponent/spin";
import Empty from "@/pages/myComponent/empty";
import { useDispatch } from "react-redux";
import PubSub from "pubsub-js";
import "../common.scss";
import styles from "./index.module.scss";

//消息类型
const msgType = [
  { id: -1, key: "all", text: "全部消息" },
  { id: 1, key: "appletsPush", text: "公众号消息" },
  { id: 2, key: "sysPush", text: "系统提醒" },
  { id: 3, key: "todoPush", text: "待办事项" },
  { id: 4, key: "appPush", text: "App消息" },
  { id: 5, key: "mailPush", text: "邮件" },
  { id: 6, key: "smsPush", text: "手机短信" },
];

// 计算事件数
function calcEventCount(sceneList) {
  let eventIdCount = 0;
  // 遍历每个场景
  for (const scene of sceneList) {
    // 遍历每个场景的事件列表
    for (const event of scene.eventList) {
      // 增加eventId的数量
      eventIdCount++;
    }
  }
  return eventIdCount;
}

// 计算开启的开关数目
function calcOpenedPushCount(eventInfo) {
  let num = 0;
  let flag=Object.keys(eventInfo).some((key) => {
    const item = eventInfo[key];
    return item==="1"
  });
  if(flag) num+=1

  return num;
}

function App() {
  const dispatch = useDispatch();
  const [isSearch, setIsSearch] = useState(false);
  const [keyword, setKeyword] = useState("");
  const [currentApp, setCurrentApp] = useState({ text: "全部应用", sysId: "" });
  const [currentType, setCurrentType] = useState({ text: "全部消息", id: -1 });
  const [dataList, setDataList] = useState([]);
  const [appList, setAppList] = useState([]);

  const { schoolId, schoolLevel } = useGetUserInfo() as any;
  console.log(useGetUserInfo())
  // 获取系统列表
  useRequest(
    async () => {
      const { data } = await getSystemListService(schoolId, '3');
      data.unshift({ sysName: "全部应用", sysId: "" });
      return data;
    },
    {
      onSuccess(result) {
        setAppList(result);
      },
    }
  );
  // 获取设置列表
  const { loading, run: refreshSystemList } = useRequest(
    async () => {
      const { data = [] } = await getSettingListService({
        sysId: currentApp.sysId,
        type: currentType.id,
        keyword,
        schoolId,
        beSchoolLevel: '3',
      });

      let resetList: any = [];
      data.forEach((i) => {
        if (!i) return;
        const {
          sysId,
          sysName,
          sceneId,
          sceneName,
          eventId,
          eventContent,
          globalPush,
          appletsPush,
          todoPush,
          sysPush,
          appPush,
          mailPush,
          smsPush,
          noticeTarget,
        } = i;
        let index = resetList.findIndex((s: any) => s.sysId === sysId);
        const eventInfo = {
          eventId,
          eventContent,
          appletsPush,
          todoPush,
          sysPush,
          appPush,
          mailPush,
          smsPush,
          noticeTarget,
        };
        // 若不存该系统在则推入一条
        // console.log("eventInfo", eventInfo);
        const openedPushCount = calcOpenedPushCount(eventInfo);
        if (index < 0) {
          resetList.push({
            sysId,
            sysName,
            globalPush,
            openedPushCount,
            sceneList: [
              {
                sceneId,
                sceneName,
                eventList: [eventInfo],
              },
            ],
          });
        } else {
          // 存在该系统
          const currentSystem = resetList[index];
          const sceneList = currentSystem.sceneList || [];
          const sIndex = sceneList.findIndex((s: any) => s.sceneId === sceneId);
          //场景不存在 新建一条场景并存入事件
          if (sIndex < 0) {
            currentSystem.openedPushCount += openedPushCount;
            currentSystem.sceneList.push({
              sceneId,
              sceneName,
              eventList: [eventInfo],
            });
          } else {
            // 场景存在 则对事件进行判断
            const currentScene = currentSystem.sceneList[sIndex];
            const eventList = currentScene.eventList || [];
            const eIndex = eventList.findIndex(
              (s: any) => s.eventId === eventId
            );
            // 事件不存在 (事件存在则不处理)
            if (eIndex < 0) {
              currentSystem.openedPushCount += openedPushCount;
              eventList.push(eventInfo);
            }
          }
        }
      });

      return resetList;
    },
    {
      manual: true,
      onSuccess(result) {
        setDataList(result);
      },
    }
  );

  useEffect(() => {
    refreshSystemList();
  }, [keyword, currentApp, currentType]);

  useEffect(() => {
    // 订阅其他页面对当前设置列表的刷新
    const refreshFn = PubSub.subscribe("refresh_setting", refreshSystemList);
    return () => {
      PubSub.unsubscribe(refreshFn);
    };
  }, []);

  // 改变系统推送状态
  function handleChangeSystemStatus(sysId: string, value: boolean,e:MouseEvent) {
    e.stopPropagation()
    const flag = value ? 1 : 0;
    changeSystemStatusService({ sysId, globalPush: flag, schoolId }).then(
      (result) => {
        if (result.code == 200) {
          Taro.showToast({
            title: `消息推送${value?"开启":"关闭"}成功`,
          });
        }
        refreshSystemList();
      }
    );
  }

  // 去详情页面
  function toDetail(system) {
    dispatch({
      type: "SET_CURRENTSYSTEM",
      data: system,
    });
    Taro.navigateTo({ url: "/pages/messagePushSetting/detail/index" });
  }

  //防抖输入
  const debounceInput = debounce((value) => {
    setKeyword(value);
  }, 500);

  return (
    <View className={styles.container}>
      <Header title="消息中心推送设置" />
      <View className={styles["content-wrapper"]}>
        {loading && <SpinLoad />}
        <View className={styles.options}>
          <View className={styles.left}>
            <LgSelepicker
              type="B"
              id="opt1"
              className={styles.dropdown}
              dataList={appList}
              changeSele={(app) => setCurrentApp(app)}
              attr="sysName"
            />
            <LgSelepicker
              type="B"
              id="opt1"
              className={styles.dropdown}
              dataList={msgType}
              changeSele={(type) => setCurrentType(type)}
              attr="text"
            />
          </View>
          <View className={styles.right}>
            {isSearch ? (
              <View className={styles.ipt}>
                <LgSearch
                  value={keyword}
                  onConfirm={(value: string) => setKeyword(value.trim())}
                  placeholder="请输入..."
                  onInput={(value: string) => debounceInput(value.trim())}
                />
              </View>
            ) : (
              <View
                className={styles["search-icon"]}
                onClick={() => setIsSearch(true)}
              ></View>
            )}
          </View>
        </View>
        <View className={styles.content}>
          {dataList.length <= 0 && !loading ? <Empty /> : null}
          {dataList.map((system) => {
            const {
              sysId,
              sysName,
              openedPushCount = 0,
              globalPush,
              sceneList = [],
            } = system;
            // console.log(system);
            const eventCount = calcEventCount(sceneList);
            return (
              <View
                key={sysId}
                className={styles["card-wrapper"]}
                onClick={(e) => toDetail(system)}
              >
                <View className={styles.top}>
                  <View className={styles.title}>{sysName}</View>
                  <View onClick={(e) => handleChangeSystemStatus(sysId, !(globalPush === "1"),e)}>
                    <Switch
                      checked={globalPush === "1"}
                      style={{
                        "--width": Taro.pxTransform(72),
                        "--height": Taro.pxTransform(42),
                        "--checked-color": "#56be56",
                      }}
                    />
                  </View>
                </View>
                <Divider
                  style={{
                    margin: `${Taro.pxTransform(24)} 0`,
                  }}
                />
                <View className={styles.bottom}>
                  <View className={styles.text}>
                    共
                    <Text style={{ color: "#333333" }}>{sceneList.length}</Text>
                    个场景,
                    <Text style={{ color: "#333333" }}>{eventCount}</Text>
                    个事件(已开启
                    <Text style={{ color: "#333333" }}>{openedPushCount}</Text>
                    个消息推送)
                  </View>
                  <View className={styles["setting-btn"]}>去设置</View>
                </View>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
export default App;
